import { ref, computed } from 'vue'
import { documentApi } from '@/modules/doc/api'
import type { Doc } from '@/modules/doc/types/doc.ts'
import { flattenDocumentTree, buildDocumentTree, sortDocuments, filterDocumentsByKeyword } from '@/utils/documentUtils'
import { toast } from '@/utils/message'

/**
 * 文档列表组合式函数
 * 封装文档列表的获取、处理和管理
 */
export function useDoc() {
  // 响应式状态
  const documents = ref<Doc[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  // 计算属性
  const documentCount = computed(() => documents.value.length)
  const hasDocuments = computed(() => documents.value.length > 0)

  /**
   * 根据命名空间获取文档列表
   * @param namespaceId 命名空间ID
   * @param options 选项配置
   */
  const fetchDocumentsByNamespace = async (
    namespaceId: string,
    options: {
      showLoading?: boolean
      showError?: boolean
      flatten?: boolean
      sort?: boolean
    } = {}
  ) => {
    const {
      showLoading = true,
      showError = true,
      flatten = true,
      sort = true
    } = options

    try {
      if (showLoading) loading.value = true
      error.value = null

      const response = await documentApi.getByNamespace(namespaceId)
      
      if (response.data) {
        let processedDocs = response.data
        
        // 是否需要展平文档树
        if (flatten) {
          processedDocs = flattenDocumentTree(processedDocs)
          
          // 展平后再排序
          if (sort) {
            processedDocs = sortDocuments(processedDocs)
          }
        } else {
          // 保持树形结构，这里直接使用返回的数据
          processedDocs = response.data
        }
        
        documents.value = processedDocs
      }

      return documents.value
    } catch (err: any) {
      const errorMessage = err.message || '获取文档列表失败'
      error.value = errorMessage
      
      if (showError) {
        toast.error(errorMessage)
      }
      
      throw err
    } finally {
      if (showLoading) loading.value = false
    }
  }

  /**
   * 获取收藏文档列表
   * @param options 选项配置
   */
  const fetchFavoriteDocuments = async (
    options: {
      showLoading?: boolean
      showError?: boolean
      flatten?: boolean
      sort?: boolean
    } = {}
  ) => {
    const {
      showLoading = true,
      showError = true,
      flatten = true,
      sort = true
    } = options

    try {
      if (showLoading) loading.value = true
      error.value = null

      const response = await documentApi.getFavorites()
      
      if (response.data) {
        let processedDocs = response.data
        
        // 是否需要展平文档树
        if (flatten) {
          processedDocs = flattenDocumentTree(processedDocs)
          
          // 展平后再排序
          if (sort) {
            processedDocs = sortDocuments(processedDocs)
          }
        } else {
          // 保持树形结构，这里直接使用返回的数据
          processedDocs = response.data
        }
        
        documents.value = processedDocs
      }

      return documents.value
    } catch (err: any) {
      const errorMessage = err.message || '获取收藏列表失败'
      error.value = errorMessage
      
      if (showError) {
        toast.error(errorMessage)
      }
      
      throw err
    } finally {
      if (showLoading) loading.value = false
    }
  }

  /**
   * 创建新文档
   * @param documentData 文档数据
   */
  const createDocument = async (documentData: Omit<Doc, 'id' | 'createdTime' | 'updatedTime' | 'children'>) => {
    try {
      loading.value = true
      
      const response = await documentApi.create(documentData)
      
      // 后端直接返回文档ID字符串
      return response.data
    } catch (err: any) {
      const errorMessage = err.message || '创建文档失败'
      toast.error(errorMessage)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 更新文档
   * @param id 文档ID
   * @param documentData 文档数据
   */
  const updateDocument = async (id: string, documentData: Omit<Doc, 'id' | 'createdTime' | 'updatedTime' | 'children'>) => {
    try {
      loading.value = true
      
      const response = await documentApi.update(id, documentData)
      
      if (response.data) {
        // 更新列表中的文档
        const index = documents.value.findIndex(doc => doc.id === id)
        if (index !== -1) {
          documents.value[index] = response.data
        }
        
        toast.success('文档更新成功')
        return response.data
      }
    } catch (err: any) {
      const errorMessage = err.message || '更新文档失败'
      toast.error(errorMessage)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 删除文档
   * @param id 文档ID
   */
  const deleteDocument = async (id: string) => {
    try {
      const confirmed = await toast.confirm('确定要删除此文档吗？', {
        title: '删除确认',
        confirmButtonText: '删除'
      })

      if (!confirmed) return false

      loading.value = true

      await documentApi.delete(id)

      // 从列表中移除
      documents.value = documents.value.filter(doc => doc.id !== id)
      return true
    } catch (err: any) {
      const errorMessage = err.message || '删除文档失败'
      toast.error(errorMessage)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 移动文档
   * @param documentId 文档ID
   * @param newParentId 新父文档ID
   * @param sortNo 排序号
   */
  const moveDocument = async (documentId: string, newParentId: string | null, sortNo: number) => {
    try {
      loading.value = true
      
      const response = await documentApi.moveDocument(documentId, newParentId, sortNo)
      
      if (response.data) {
        // 更新本地文档的父级和排序
        const doc = documents.value.find(d => d.id === documentId)
        if (doc) {
          doc.parentId = newParentId
          doc.sortNo = sortNo
          
          // 重新排序
          documents.value = sortDocuments(documents.value)
        }
        
        toast.success('文档移动成功')
        return true
      }
    } catch (err: any) {
      const errorMessage = err.message || '移动文档失败'
      toast.error(errorMessage)
      throw err
    } finally {
      loading.value = false
    }
  }

  /**
   * 搜索文档
   * @param keyword 搜索关键词
   */
  const searchDocuments = (keyword: string): Doc[] => {
    return filterDocumentsByKeyword(documents.value, keyword)
  }

  /**
   * 构建文档树
   */
  const getDocumentTree = (): Doc[] => {
    return buildDocumentTree(documents.value)
  }

  /**
   * 清空文档列表
   */
  const clearDocuments = () => {
    documents.value = []
    error.value = null
    loading.value = false
  }

  /**
   * 重新加载文档列表
   */
  const reloadDocuments = async (namespaceId?: string) => {
    if (namespaceId) {
      await fetchDocumentsByNamespace(namespaceId)
    }
  }

  return {
    // 状态
    documents,
    loading,
    error,
    
    // 计算属性
    documentCount,
    hasDocuments,
    
    // 方法
    fetchDocumentsByNamespace,
    fetchFavoriteDocuments,
    createDocument,
    updateDocument,
    deleteDocument,
    moveDocument,
    searchDocuments,
    getDocumentTree,
    clearDocuments,
    reloadDocuments
  }
}